﻿using AutoMapper;
using B.Z.BasicData.Domain.Entity.Authorize;
using B.Z.BasicData.ErrorCode;
using B.Z.BasicData.Infrastructure;
using MediatR;

namespace B.Z.BasicData.API.Write.Application.Role
{
    public class RoleUpdateCommandHandler : IRequestHandler<RoleUpdateCommand, APIResult<int>>
    {
        private readonly IBaseRepository<T_Role> roleRepository;
        private readonly IBaseRepository<T_UserRole> urRepository;
        private readonly IMapper mapper;

        public RoleUpdateCommandHandler(IBaseRepository<T_Role> roleRepository, IMapper mapper, IBaseRepository<T_UserRole> urRepository)
        {
            this.roleRepository = roleRepository;
            this.mapper = mapper;
            this.urRepository = urRepository;
        }
        public async Task<APIResult<int>> Handle(RoleUpdateCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();


            if (string.IsNullOrEmpty(request.isDelorUpdate)) 
            {
                result.Code = APIEnum.ok;
                result.Message = "删除成功";
                var delrole = mapper.Map<T_Role>(request);
                var list = urRepository.GetAll().Where(p => p.Rid == delrole.Id);
                if (list.Count() > 0) 
                {
                    result.Code = APIEnum.faile;
                    result.Message = "存在员工角色绑定关系，请先解除关系";
                    return await Task.FromResult(result);
                }
                delrole.IsDelete = true;
                result.Data = await roleRepository.Update(delrole);
                return await Task.FromResult(result);

            }

            result.Code = APIEnum.ok;
            result.Message = "修改成功";
            var roles = roleRepository.GetAll().Where(p => p.RoleName == request.RoleName&&p.Id!=request.Id);
            if (roles.Count() > 0)
            {
                result.Code = APIEnum.faile;
                result.Message = "角色名称已存在";
                return await Task.FromResult(result);
            }
            var role = mapper.Map<T_Role>(request);
            role.UpdateTime = DateTime.Now;
            result.Data = await roleRepository.Update(role);
            return await Task.FromResult(result);
        }
    }
}
